<template>
  <!--组织结构管理页面-->
  <a-row>
    <a-col :span="5">
      <a-button style="margin-left: 10px" icon="plus-square" size="small" @click="addDepartment()">
        新增
      </a-button>
      <div>
        <a-tree
          :treeData="treeData"
          :replaceFields="replaceFields"
          :selectedKeys="selectedKeys"
          :defaultExpandAll="true"
          @select="treeSelect"
        >
        </a-tree>
        <DepartmentModalAdd ref="modal" @call="addSuccess"/>
      </div>
    </a-col>
    <a-col :span="1"></a-col>
    <a-col :span="18">
      <DepartmentUpdate ref="update" @refresh="queryTree" :deptId="selectedKey"/>
    </a-col>
  </a-row>
</template>

<script>
import api from './system'
import DepartmentUpdate from './components/DepartmentUpdate'
import DepartmentModalAdd from './modal/DepartmentModalAdd'

// 组织结构管理页面
export default {
  name: 'DepartmentPage',
  components: {
    DepartmentUpdate,
    DepartmentModalAdd
  },
  data () {
    return {
      treeData: [],
      selectedKey: '',
      replaceFields: { children: 'children', title: 'name', key: 'id' }
    }
  },
  computed: {
    selectedKeys () {
      return [this.selectedKey]
    }
  },
  created () {
    this.queryTree(true)
  },
  methods: {
    // 获取组织结构树
    queryTree (first) {
      this.axios.post(api.department.getDepartmentTree)
        .then((res) => {
          console.log(res)
          const data = res.data || []
          if (data && data.length > 0 && first) {
            this.selectedKey = data[0].id
          }
          this.treeData = res.data
        })
        .catch((error) => {
          console.log('请求异常...', error)
        })
    },
    // 新增成功之后，1、重新获取树数据 2、将新增成功的节点选中
    addSuccess (id) {
      this.selectedKey = id
      this.queryTree()
    },
    // 树节点选中事件
    treeSelect (selectedKeys, info) {
      info.selected = true
      const selectedKey = selectedKeys[0]
      if (selectedKey) {
        this.selectedKey = selectedKey
      }
    },
    // 新增
    addDepartment () {
      this.$refs.modal.showModal()
    }
  }
}
</script>
